package com.atguigu.schedule.controller;

import com.atguigu.schedule.common.Result;
import com.atguigu.schedule.common.ResultCodeEnum;
import com.atguigu.schedule.pojo.*;
import com.atguigu.schedule.service.PasswordResetService;
import com.atguigu.schedule.service.SysUserService;
import com.atguigu.schedule.service.VerificationCodeService;
import com.atguigu.schedule.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户控制器
 * 
 * @author atguigu
 * @since 2024
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
    
    @Autowired
    private SysUserService userService;
    
    @Autowired
    private PasswordResetService passwordResetService;
    
    @Autowired
    private VerificationCodeService verificationCodeService;

    /**
     * 注册时，接收要注册的用户名，校验用户名是否被占用的业务接口
     * 
     * @param username 用户名
     * @return 检查结果
     */
    @GetMapping("/checkUsername")
    public Result<String> checkUsernameUsed(@RequestParam String username) {
        // 调用服务层业务处理方法查询该用户名是否有对应的用户
        SysUser sysUser = userService.findByUsername(username);
        
        // 如果有 响应 已占用，如果没有 响应 可用
        return sysUser != null ? 
            Result.build(null, ResultCodeEnum.USERNAME_USED) : 
            Result.ok("用户名可用");
    }

    /**
     * 检查用户名是否存在（用于密码重置流程）
     * 
     * @param username 用户名
     * @return 检查结果
     */
    @GetMapping("/checkUsernameExists")
    public Result<String> checkUsernameExists(@RequestParam String username) {
        // 调用服务层业务处理方法查询该用户名是否有对应的用户
        SysUser sysUser = userService.findByUsername(username);
        
        // 如果存在 响应 成功，如果不存在 响应 用户名不存在
        return sysUser != null ? 
            Result.ok("用户名存在") : 
            Result.build(null, ResultCodeEnum.USERNAME_NOT_EXISTS);
    }

    /**
     * 接收用户登录请求，完成登录业务接口
     * 
     * @param sysUser 登录用户信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody SysUser sysUser) {
        // 调用服务层方法，根据用户名查询用户信息
        SysUser loginUser = userService.findByUsername(sysUser.getUsername());

        if (loginUser == null) {
            // 用户名有误
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        } else if (!MD5Util.encrypt(sysUser.getUserPwd()).equals(loginUser.getUserPwd())) {
            // 密码有误
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        } else {
            // 登录成功，将登录的用户信息返回
            Map<String, Object> data = new HashMap<>();
            loginUser.setUserPwd("");
            data.put("loginUser", loginUser);
            return Result.ok(data);
        }
    }





    /**
     * 接收用户注册请求的业务处理方法
     * 
     * @param registUser 注册用户信息
     * @return 注册结果
     */
    @PostMapping("/regist")
    public Result<String> regist(@RequestBody SysUser registUser) {
        // 调用服务方法，完成注册功能
        int rows = userService.regist(registUser);
        
        // 根据注册结果（成功  失败）返回结果
        if (rows < 1) {
            return Result.build(null, ResultCodeEnum.USERNAME_USED);
        } else {
            return Result.ok("注册成功");
        }
    }

    /**
     * 带验证码的注册接口
     * 
     * @param request 注册请求（包含验证码）
     * @return 注册结果
     */
    @PostMapping("/registWithCode")
    public Result<String> registWithCode(@RequestBody RegisterRequest request) {
        try {
            // 1. 验证验证码
            Result<Boolean> verifyResult = verificationCodeService.verifyCode(
                request.getPhone(),
                request.getVerificationCode()
            );
            
            if (verifyResult.getCode() != 200 || !verifyResult.getData()) {
                return Result.build(null, 400, "验证码错误或已过期");
            }
            
            // 2. 创建用户对象
            SysUser registUser = new SysUser();
            registUser.setUsername(request.getUsername());
            registUser.setUserPwd(request.getUserPwd());
            registUser.setPhone(request.getPhone());
            
            // 3. 调用服务方法，完成注册功能
            int rows = userService.regist(registUser);
            
            // 4. 根据注册结果返回
            if (rows < 1) {
                return Result.build(null, ResultCodeEnum.USERNAME_USED);
            } else {
                return Result.ok("注册成功");
            }
            
        } catch (Exception e) {
            System.err.println("注册失败: " + e.getMessage());
            return Result.build(null, 500, "注册失败");
        }
    }

    /**
     * 获取所有活跃的安全问题
     * 
     * @return 安全问题列表
     */
    @GetMapping("/securityQuestions")
    public Result<List<SecurityQuestion>> getAllSecurityQuestions() {
        List<SecurityQuestion> questions = passwordResetService.getAllActiveSecurityQuestions();
        return Result.ok(questions);
    }

    /**
     * 获取用户的安全问题
     * 
     * @param username 用户名
     * @return 用户的安全问题列表
     */
    @GetMapping("/userSecurityQuestions")
    public Result<List<SecurityQuestion>> getUserSecurityQuestions(@RequestParam String username) {
        List<SecurityQuestion> questions = passwordResetService.getUserSecurityQuestions(username);
        if (questions == null) {
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        return Result.ok(questions);
    }

    /**
     * 验证安全问题答案
     * 
     * @param request 安全问题答案验证请求
     * @return 验证结果
     */
    @PostMapping("/verifySecurityAnswers")
    public Result<Boolean> verifySecurityAnswers(@RequestBody SecurityAnswersRequest request) {
        boolean isValid = passwordResetService.verifySecurityAnswers(request);
        return Result.ok(isValid);
    }

    /**
     * 重置密码
     * 
     * @param request 密码重置请求
     * @return 重置结果
     */
    @PostMapping("/resetPassword")
    public Result<String> resetPassword(@RequestBody PasswordResetRequest request) {
        String result = passwordResetService.resetPassword(request);
        if (result.contains("失败") || result.contains("不够") || result.contains("不存在")) {
            return Result.build(null, ResultCodeEnum.SYSTEM_ERROR.getCode(), result);
        }
        return Result.ok(result);
    }

    /**
     * 设置用户安全问题答案（注册时使用）
     * 
     * @param request 包含用户名和安全问题的注册请求
     * @return 设置结果
     */
    @PostMapping("/setSecurityAnswers")
    public Result<String> setSecurityAnswers(@RequestBody Map<String, Object> request) {
        String username = (String) request.get("username");
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> securityQuestions = (List<Map<String, Object>>) request.get("securityQuestions");
        
        SysUser user = userService.findByUsername(username);
        if (user == null) {
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        
        List<SecurityQuestionRequest> questionRequests = securityQuestions.stream()
                .map(q -> new SecurityQuestionRequest(
                        (Integer) q.get("questionId"),
                        (String) q.get("answer")
                ))
                .toList();
        
        boolean success = passwordResetService.setUserSecurityAnswers(user.getUid(), questionRequests);
        if (success) {
            return Result.ok("安全问题设置成功");
        } else {
            return Result.build(null, ResultCodeEnum.SECURITY_QUESTIONS_SET_FAILED);
        }
    }

}
